﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.IO;

namespace Sustainalytics.PregenerateScreeningReports.Service
{
    class OldFilesCleaner
    {
        public OldFilesCleaner(string path, int daysToPreserve = 10)
        {   
            var limit = DateTime.UtcNow.Date.AddDays(-daysToPreserve);
            task = Task.Run(() => 
            {
               Directory.GetFiles(path)
                      .Select(f => new FileInfo(f))
                      .Where(f => f.CreationTimeUtc < limit)
                      .ToList()
                      .ForEach(f => { try { f.Delete(); } catch { /*on purpose*/} });
            });
        }

         public bool Wait(int maxWaitInterval = 5000)
         {
            return  task.Wait(maxWaitInterval);
         }

        Task task;
    }
}
